import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '逻辑优化计数器 App',
      theme: ThemeData(
        primarySwatch: Colors.deepPurple,
        visualDensity: VisualDensity.adaptivePlatformDensity,
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '逻辑优化计数器'),
    );
  }
}

enum IncrementStep { one, five, ten, twenty } // 增加了步长20

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  final TextEditingController _textController = TextEditingController();
  double _sliderValue = 0;

  bool _isIncrementDoubled = false; // Switch 状态: 增量翻倍
  IncrementStep _selectedStep = IncrementStep.one; // Radio 状态: 步长选择

  // 奖励系统状态
  bool _milestoneRewardFiftyClaimed = false; // 首次达到50的奖励是否已领取
  bool _milestoneRewardHundredClaimed = false; // 首次达到100的奖励是否已领取
  String _lastRewardMessage = ""; // 用于显示奖励信息

  // 获取当前选择的步长值
  int get _currentStepValue {
    switch (_selectedStep) {
      case IncrementStep.one:
        return 1;
      case IncrementStep.five:
        return 5;
      case IncrementStep.ten:
        return 10;
      case IncrementStep.twenty:
        return 20;
    }
  }

  // 更新所有关联组件的显示
  void _updateAllDisplays() {
    _sliderValue = _counter.toDouble().clamp(0, 200); // 假设滑块最大值为200
    _textController.text = _counter.toString();
  }

  // 检查并触发奖励
  void _checkAndApplyRewards() {
    String rewardAchieved = "";
    if (_counter >= 50 && !_milestoneRewardFiftyClaimed) {
      setState(() {
        _counter += 10; // 奖励：额外增加10
        _milestoneRewardFiftyClaimed = true;
        rewardAchieved = "恭喜达到50！奖励10点！";
      });
    }
    if (_counter >= 100 && !_milestoneRewardHundredClaimed) {
      setState(() {
        _counter += 25; // 奖励：额外增加25
        _milestoneRewardHundredClaimed = true;
        rewardAchieved =
            (rewardAchieved.isNotEmpty ? "$rewardAchieved\n" : "") +
            "太棒了达到100！超级奖励25点！";
        _isIncrementDoubled = true; // 额外奖励：开启增量翻倍
      });
    }

    if (rewardAchieved.isNotEmpty) {
      setState(() {
        _lastRewardMessage = rewardAchieved;
      });
      // 短暂显示奖励信息后清除
      Future.delayed(const Duration(seconds: 4), () {
        if (mounted) {
          // 检查组件是否还在树中
          setState(() {
            _lastRewardMessage = "";
          });
        }
      });
    }
    _updateAllDisplays(); // 更新显示，因为奖励可能改变了counter
  }

  void _incrementCounter() {
    setState(() {
      int incrementAmount = _currentStepValue;
      if (_isIncrementDoubled) {
        incrementAmount *= 2;
      }
      _counter += incrementAmount;
      _checkAndApplyRewards(); // 每次增加后检查奖励
      _updateAllDisplays();
    });
  }

  void _decrementCounter() {
    setState(() {
      _counter -= _currentStepValue;
      if (_counter < 0) _counter = 0;
      // 减少时一般不触发奖励，但可以根据需求设计
      _updateAllDisplays();
    });
  }

  void _setCounterFromSlider(double value) {
    setState(() {
      _counter = value.round();
      _checkAndApplyRewards(); // 通过滑块设置也检查奖励
      _updateAllDisplays();
    });
  }

  void _setCounterFromTextField(String value) {
    setState(() {
      int? newValue = int.tryParse(value);
      if (newValue != null) {
        _counter = newValue;
        if (_counter < 0) _counter = 0;
      }
      _checkAndApplyRewards(); // 通过输入框设置也检查奖励
      _updateAllDisplays();
    });
  }

  void _resetCounter() {
    setState(() {
      _counter = 0;
      _isIncrementDoubled = false;
      _selectedStep = IncrementStep.one;
      _milestoneRewardFiftyClaimed = false;
      _milestoneRewardHundredClaimed = false;
      _lastRewardMessage = "计数器已重置";
      _updateAllDisplays();
      Future.delayed(const Duration(seconds: 2), () {
        if (mounted) {
          setState(() {
            _lastRewardMessage = "";
          });
        }
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _updateAllDisplays();
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              // 奖励信息显示区域
              if (_lastRewardMessage.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.only(bottom: 15.0),
                  child: Card(
                    color: Colors.green[100],
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Text(
                        _lastRewardMessage,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.green[800],
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),

              const Text(
                '当前计数值:',
                style: TextStyle(fontSize: 24, color: Colors.blueGrey),
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.displayMedium?.copyWith(
                  fontWeight: FontWeight.bold,
                  color: Theme.of(context).colorScheme.primary,
                ),
              ),
              const SizedBox(height: 20),

              // 组件1: Slider
              Card(
                elevation: 2,
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    children: [
                      const Text(
                        '滑动条设置 (0-200):',
                        style: TextStyle(fontSize: 16),
                      ),
                      Slider(
                        value: _sliderValue,
                        min: 0,
                        max: 200, // 调整了最大值
                        divisions: 200,
                        label: _sliderValue.round().toString(),
                        onChanged: _setCounterFromSlider,
                        activeColor: Colors.purpleAccent,
                        inactiveColor: Colors.purple[100],
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 15),

              // 组件2: TextField
              Card(
                elevation: 2,
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    children: [
                      const Text('输入框设置:', style: TextStyle(fontSize: 16)),
                      Padding(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 30.0,
                          vertical: 8.0,
                        ),
                        child: TextField(
                          controller: _textController,
                          keyboardType: TextInputType.number,
                          inputFormatters: <TextInputFormatter>[
                            FilteringTextInputFormatter.digitsOnly,
                          ],
                          textAlign: TextAlign.center,
                          style: const TextStyle(fontSize: 20),
                          decoration: InputDecoration(
                            hintText: '输入数值',
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            contentPadding: const EdgeInsets.symmetric(
                              vertical: 10,
                            ),
                          ),
                        ),
                      ),
                      ElevatedButton.icon(
                        icon: const Icon(Icons.check_circle_outline),
                        label: const Text('确认输入'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.purple[100],
                        ),
                        onPressed: () {
                          _setCounterFromTextField(_textController.text);
                          FocusScope.of(context).unfocus();
                        },
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 20),

              const Divider(thickness: 1, height: 30),
              Text("高级控制选项", style: Theme.of(context).textTheme.titleLarge),
              const SizedBox(height: 15),

              // 组件3: Switch (增量翻倍)
              Card(
                elevation: 2,
                child: SwitchListTile(
                  title: const Text('增量翻倍模式', style: TextStyle(fontSize: 16)),
                  value: _isIncrementDoubled,
                  onChanged: (bool value) {
                    setState(() {
                      _isIncrementDoubled = value;
                      _lastRewardMessage = value ? "增量翻倍已开启！" : "增量翻倍已关闭。";
                    });
                    Future.delayed(const Duration(seconds: 2), () {
                      if (mounted) {
                        setState(() {
                          _lastRewardMessage = "";
                        });
                      }
                    });
                  },
                  activeColor: Colors.orangeAccent,
                  secondary: const Icon(Icons.double_arrow_rounded),
                ),
              ),
              const SizedBox(height: 10),

              // 组件4: Radio Buttons (选择步长)
              Card(
                elevation: 2,
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text('选择增/减步长:', style: TextStyle(fontSize: 16)),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children:
                            IncrementStep.values.map((step) {
                              String stepLabel;
                              switch (step) {
                                case IncrementStep.one:
                                  stepLabel = "1";
                                  break;
                                case IncrementStep.five:
                                  stepLabel = "5";
                                  break;
                                case IncrementStep.ten:
                                  stepLabel = "10";
                                  break;
                                case IncrementStep.twenty:
                                  stepLabel = "20";
                                  break;
                              }
                              return Column(
                                // 使用 Column 来组合 Radio 和 Text
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  Radio<IncrementStep>(
                                    value: step,
                                    groupValue: _selectedStep,
                                    onChanged: (IncrementStep? value) {
                                      if (value != null) {
                                        setState(() {
                                          _selectedStep = value;
                                        });
                                      }
                                    },
                                  ),
                                  Text(stepLabel),
                                ],
                              );
                            }).toList(),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 20),

              // 组件5: 奖励系统信息 (通过顶部的 _lastRewardMessage 显示)
              // 这里可以放一个说明性的文本，或者让顶部的消息区域承担此功能。
              // 为了满足5个组件的明确性，可以加一个简单的Text说明
              Card(
                elevation: 1,
                color: Colors.blueGrey[50],
                child: const Padding(
                  padding: EdgeInsets.all(12.0),
                  child: Text(
                    "🏆 奖励系统：\n- 首次达到50点: 额外+10点\n- 首次达到100点: 额外+25点 & 开启增量翻倍",
                    style: TextStyle(fontSize: 14, color: Colors.blueGrey),
                    textAlign: TextAlign.center,
                  ),
                ),
              ),

              const SizedBox(height: 25),

              // 主要操作按钮
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  FloatingActionButton.extended(
                    heroTag: "decrement_button", // 确保 heroTag 唯一
                    onPressed: _decrementCounter,
                    tooltip: '减少 ${_currentStepValue}',
                    icon: const Icon(Icons.remove_circle_outline),
                    label: Text("减 ${_currentStepValue}"),
                    backgroundColor: Colors.red[300],
                  ),
                  ElevatedButton.icon(
                    icon: const Icon(Icons.refresh_rounded),
                    label: const Text('全部重置'),
                    onPressed: _resetCounter,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey[400],
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 12,
                      ),
                    ),
                  ),
                  FloatingActionButton.extended(
                    heroTag: "increment_button", // 确保 heroTag 唯一
                    onPressed: _incrementCounter,
                    tooltip:
                        '增加 ${_currentStepValue * (_isIncrementDoubled ? 2 : 1)}',
                    icon: const Icon(Icons.add_circle_outline),
                    label: Text(
                      "加 ${_currentStepValue * (_isIncrementDoubled ? 2 : 1)}",
                    ),
                    backgroundColor: Colors.green[400],
                  ),
                ],
              ),
              const SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }
}
